package com.hw.hcit.feature;

import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hw.hcit.R;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;

public class WifiTest extends JTestItem implements OnClickListener {
    private static final String LOG_TAG = "WifiTest ";
    private static final int SCAN_INTERVAL = 1000;
    private static final int OUT_TIME = 3000;
    private static final int REFRESH_LIST = 0;
    private int tickCount = 0;
    private Context mContext;
    private ListView mListView;
    private WifiManager mWifiManager;
    private WifiLock mWifiLock;
    private List<ScanResult> wifiScanResult;
    private boolean scanResultAvailabe = false;
    private ArrayAdapter<String> wifiArrayAdapter;
    private boolean tested = false;
    private boolean powerClicked = false;
    private Button mButton1,mButton2;
	private TextView textView;

    public WifiTest(JCtrlCallback cb) {
        super(cb);
    }

    public WifiTest() {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.wifi_test, container, false);
        mListView = (ListView) rootView.findViewById(R.id.wifi_list);
        wifiArrayAdapter = new ArrayAdapter<String>(mContext,
                android.R.layout.simple_list_item_1);
        mListView.setAdapter(wifiArrayAdapter);
        textView = (TextView) rootView.findViewById(R.id.textView1);
		mButton1 = (Button) rootView.findViewById(R.id.button1);
		mButton2 = (Button) rootView.findViewById(R.id.button2);
		mButton1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(24, 'P');
					} else {
						rewriteOneByteOfNv2499(55, 'P');
					}
				}
				 testFinish(true, 1, true);
				
			}
		});
		mButton2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(24, 'F');
					} else {
						rewriteOneByteOfNv2499(55, 'F');
					}
				}
				testFinish(false, 1, false);
				
			}
		});
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        mContext = activity;
        mWifiManager = (WifiManager) mContext
                .getSystemService(Context.WIFI_SERVICE);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
         tested = false;
         powerClicked = false;
         mButton1.setEnabled(false);
         mButton2.setEnabled(false);
        /** Keep Wi-Fi awake */
        mWifiLock = mWifiManager.createWifiLock(
                WifiManager.WIFI_MODE_SCAN_ONLY, "WiFi");
        if (false == mWifiLock.isHeld())
            mWifiLock.acquire();

        switch (mWifiManager.getWifiState()) {
        case WifiManager.WIFI_STATE_DISABLED:
            Toast.makeText(mContext, "WiFi not enabled!", Toast.LENGTH_LONG)
                    .show();
            break;
        case WifiManager.WIFI_STATE_DISABLING:
            //
            break;
        case WifiManager.WIFI_STATE_UNKNOWN:
            Toast.makeText(mContext, "WiFi state unknown!", Toast.LENGTH_LONG)
                    .show();
            break;
        default:
            break;
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mContext.registerReceiver(mReceiver, filter);

        tickCount = 0;
        mCountDownTimer.start();

    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mContext.unregisterReceiver(mReceiver);
        scanResultAvailabe = false;
        wifiArrayAdapter.clear();
        try {
            mCountDownTimer.cancel();
            if (true == mWifiLock.isHeld())
                mWifiLock.release();
        } catch (Exception e) {
            Log.d(LOG_TAG , LOG_TAG + e);
        }

    }

    @Override
    public boolean getResult() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public String getResultInfo() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void startTest() {
        // TODO Auto-generated method stub

    }

    @Override
    public void stopTest() {
        // TODO Auto-generated method stub

    }

    public void refresh() {

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        public void onReceive(Context c, Intent intent) {

            Log.d(LOG_TAG ,
                    intent.getAction() + " " + mWifiManager.getWifiState());
            if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent
                    .getAction())) {
                if (!scanResultAvailabe) {
                    wifiScanResult = mWifiManager.getScanResults();
                    scanResultAvailabe = true;
                    mHandler.sendEmptyMessage(REFRESH_LIST);
                }
            }
        }

    };

    CountDownTimer mCountDownTimer = new CountDownTimer(OUT_TIME, SCAN_INTERVAL) {

        @Override
        public void onFinish() {

            Log.d(LOG_TAG , LOG_TAG + "Timer Finish");
            if (wifiScanResult != null && wifiArrayAdapter.getCount()==0) {
                //
                mButton2.setEnabled(true);
                textView.setText(getString(R.string.wifi_scan_fail));
            }
        }

        @Override
        public void onTick(long arg0) {

            tickCount++;
            Log.d(LOG_TAG , LOG_TAG + "Timer Tick " + tickCount);
            // At least conduct startScan() 3 times to ensure wifi's scan
            if (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
                mWifiManager.startScan();
                // When screen is dim, SCAN_RESULTS_AVAILABLE_ACTION cannot be
                // got.
                // So get it actively
                if (tickCount >= 3 && !scanResultAvailabe) {
                    wifiScanResult = mWifiManager.getScanResults();
                    scanResultAvailabe = true;
                    mHandler.sendEmptyMessage(REFRESH_LIST);
                }
            }

        }
    };

    Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {

            if (wifiScanResult != null && wifiScanResult.size() > 0) {
                wifiArrayAdapter.clear();
                for (int i = 0; i < wifiScanResult.size(); i++) {
                    Log.d(LOG_TAG , "" + wifiScanResult.get(i));
                    if(wifiScanResult.get(i).SSID.equals("HY333")){
                    	 wifiArrayAdapter.add("SSID:"+wifiScanResult.get(i).SSID+"               level:"+wifiScanResult.get(i).level);
                    	 mButton1.setEnabled(true);
                    	 textView.setText(getString(R.string.wifi_scan_success));
                    	 mCountDownTimer.cancel();
                    }
                   
                }
                updateAdapter();
            } else {
                scanResultAvailabe = false;
            }
        }
    };

    public void updateAdapter() {
        wifiArrayAdapter.notifyDataSetChanged();
    }
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        return true;
    }
    /*@Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
             dissmissPowerClicked();
            Log.d(LOG_TAG , " --------->KeyEvent.KEYCODE_VOLUME_DOWN");
            if (powerClicked) {
                Log.d(LOG_TAG ,
                        "powerClicked --------->KeyEvent.KEYCODE_VOLUME_DOWN");
                testFinish(false, 1, false);
                return true;
            }
            if (tested) {
                Log.d(LOG_TAG ,
                        "tested --------->KeyEvent.KEYCODE_VOLUME_DOWN");
                testFinish(true, 1, true);
            } else {
                Log.d(LOG_TAG , " ----111----->showTestUncomplete");
                showTestUncomplete();
            }
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
             dissmissPowerClicked();
            testFinish(true, -1, true);
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
            Log.d(LOG_TAG , "powerClicked --------->KeyEvent.KEYCODE_POWER");
            powerClicked = true;
            showPowerClicked();
        }
        return true;
    }*/

}
